<?
 header('Content-Type: text/html; charset=utf-8'); 
include "./php/lib_dbconnection.php";
$cityId = $_GET["city_id"];
$query_result = mysql_query("SELECT * FROM cities WHERE city_id=$cityId");
if(!$query_result){
	exit(mysql_error());
};
?>

<!DOCTYPE HTML>
<html id="html" lang="en">
    <head>
        <meta charset="utf-8">
    	<title>Tap'n'Map - <?echo mysql_result($query_result, 0, "city_name")?></title>
        <link rel="stylesheet" href="./css/style.css" media="screen"></link>
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.8/dijit/themes/claro/claro.css" media="screen"></link>
        <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.8/dojo/dojo.js"        ></script>
        <script type='text/javascript' src='./js/jquery/js/jquery-1.7.1.min.js'         ></script>
        <script type='text/javascript' src='./js/jquery/js/jquery.mousewheel.min.js'    ></script>
        <script type='text/javascript' src='./js/API/TToolTip.js'                       ></script>
        <script type='text/javascript' src='./js/API/TPlanEngine.js'                    ></script>
        <script type='text/javascript' src='./js/TMap/TMap.js'                          ></script>
        <style type="text/css">
            #search_button{
                font-family:                Helvetica, Arial, 'Liberation Sans', FreeSans, sans-serif; 
                display:                    inline;
                outline-color:              #222;
                outline-style:              none;
                outline-width:              0px;
                position:                   static;
                padding:                    1%;
                color:                      white;
                border-top-color:           #64D0E7;
                border-radius:              20%/30%;
                border-top-style:           solid;
                border-top-width:           1px;
                font-weight:                bold;
                text-shadow:                rgba(0, 0, 0, 0.496094) 0px -1px 0px;
                background-image: -webkit-linear-gradient(top, #00B0D8, #0088C4);
                background-image: -moz-linear-gradient(top, #00B0D8, #0088C4);
                background-image: -o-linear-gradient(top, #00B0D8, #0088C4);
                background-image: -ms-linear-gradient(top, #00B0D8, #0088C4);
                background-image: linear-gradient(top, #00B0D8, #0088C4);
                margin-top:                 5%;
                margin-bottom:              5%;
            }
            a:hover{
                color: blue;
                text-decoration: underline;
                cursor: pointer;
            }
        </style>
    </head>
    <body id="body" class="claro">
        <div id="testElement" style="visibility: hidden; display: block; position: aboslute;">A</div>
        <div id="appLayout" class="demoLayout" data-dojo-type="dijit.layout.BorderContainer" data-dojo-props="design: 'headline'">
            <div id="centralPanel" class="centerPanel" data-dojo-type="dijit.layout.TabContainer" data-dojo-props="region: 'center', tabPosition: 'bottom'" style="overflow: hidden !important;">
                <div id="city_tab" data-dojo-type="dijit/layout/ContentPane" title="карта города">
                    <div id="city_map"      style="width: 100%; height: 100%; "></div>    
                </div>
                <div id="building_tab" data-dojo-type="dijit/layout/ContentPane" title="план здания" style="overflow: hidden !important;">
                    <div id="building_plan" style="width: 100%; height: 100%; overflow: hidden !important;"></div>
                </div>
            </div>
            <div class="edgePanel" data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region: 'top'">
                <div style="width: 21% !important; display: block-inline;  float: left; text-align: center;">
                    <a href="./index.php">
                        <img src="./img/logo.svg" style="display: inline; width: 100%;"></img>
                    </a>
                </div>
                <div id="search_panel" style="width: 70% !important; display: block-inline; float: left; text-align: center; padding: 1%;">
                    <input id="search_box" style="width: 50%" placeholder="начните печатать название искомого здания здесь"></input>
                    <div id="search_button">Найти</div>
                </div>
            </div>
            <div id="leftCol" class="edgePanel" data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region: 'left', splitter: true" style="width: 20%;"></div>
        </div>
    </body>
    <script type="text/javascript">
        //=========================================================
        // Global constants
        var map;
        var planTabButton;
        var testElement = document.getElementById("testElement");
        var lineHeight = testElement.clientHeight;
        var searchResultPanel = $("#leftCol");
        var savedContexts;
        var currentPlaceId = null;
        //=========================================================

        //=========================================================
        // Context object
        function Context(actionElement){
            this.searchString  = null;
            this.searchResults = null;
            this.actionElement = actionElement;
        };
        //=========================================================

        //=========================================================
        // Context helpers
        function backUpContext(index){
            savedContexts.contexts[index].searchResults = searchResultPanel.html();
            savedContexts.contexts[index].searchString = $("#search_box").val();
        };
        function setContext(index){
            searchResultPanel.html(savedContexts.contexts[index].searchResults);
            $("#search_box").val(savedContexts.contexts[index].searchString);
        };
        function toggleContext(){
            savedContexts.contexts[savedContexts.index].actionElement.unbind('click');
            backUpContext(savedContexts.index)
            savedContexts.index += 1;
            savedContexts.index %= 2;
            setContext(savedContexts.index);
            savedContexts.contexts[savedContexts.index].actionElement.click(toggleContext);
        };
        //=========================================================


        document.getElementById("body").removeChild(testElement);
		function goToPlanTab(){
			var event = document.createEvent("MouseEvents");
            event.initEvent("click","true","true");
            planTabButton.dispatchEvent(event);
		};
        function loadPlan(plan_id){
            $.get("./php/getplan.php?plan_id="+plan_id, 
                function(data){
                    tpe.setUpPlanFromText(data);
                }
                );
        };
        function loadPlaceInfo(place_id){
            searchResultPanel.html(null);
            $.get("./php/get_malldescription.php",
                    {
                        place_id: place_id,
                    },
                    function(data){
                        var placeInfo = $.parseJSON(data);
                        var placeInfoContainer = $('<div/>',{
                            id: placeInfo,
                        });
                        placeInfoContainer.append($("<a/>", {html: "<strong>"+placeInfo.place_name+"</strong><br>"}));
                        placeInfoContainer.append($("<a/>", {html: "<img src='./img/marker.svg' style='width: "+(lineHeight*1.25)+"px; height: "+(lineHeight*1.25)+"px;'/> "+placeInfo.place_address + '<br>'}));
                        placeInfoContainer.append($("<a/>", {html: "<img src='./img/call.svg' style='width: "+(lineHeight*1.25)+"px; height: "+(lineHeight*1.25)+"px;'/> "+placeInfo.place_telephone + '<br>'}));
                        placeInfoContainer.append($("<a/>", {html: "<img src='./img/letter.svg' style='width: "+(lineHeight*1.25)+"px; height: "+(lineHeight*1.25)+"px;'/><a href='mailto:"+placeInfo.place_email+"'>"+placeInfo.place_email+'</a><br>'}));
                        placeInfoContainer.append($("<a/>", {html: "<img src='./img/www.svg' style='width: "+(lineHeight*1.25)+"px; height: "+(lineHeight*1.25)+"px;'/><a href='"+placeInfo.place_site+"'>официальный сайт</a><br>"}));
                        searchResultPanel.append(placeInfoContainer);
                    }
                  );
        };
        function onPlaceMarkClick(plan_id){
            currentPlaceId = plan_id;
            goToPlanTab();
            loadPlan(plan_id);
            loadPlaceInfo(plan_id);
        };
        function setUpSearchPlaceHolder(){
            if(savedContexts.index % 2 == 0){
                searchResultPanel.html("<div><h1>Tap'n'Map</h1><br>онлайн сервис, который всегда поможет вам соориентироваться внутри здания и найти все, что вам нужно</div>");
            }else{
                loadPlaceInfo(currentPlaceId);
            }
        };
        function removeSearchPlaceHolder(){
            searchResultPanel.html(null);
        };
        function prepareSearchResults(searchPattern){
            removeSearchPlaceHolder();
            searchResultPanel.append(
                $(
                    "<div/>",
                    {
                        html: "<strong>Результаты поиска: '"+searchPattern+"'</strong>",
                        style : "margin-bottom: 5%;",
                    }
                )
            );
            searchResultPanel.append(
                $(
                    "<div/>",
                    {id: "search_results"}
                )
            );
        };
        function preparePlaceDetailedResult(result){
            var detailString = "";
            if((result.place_address != "") && (result.place_address != null) && (result.place_address != undefined)){
                detailString += "<img src='./img/marker.svg' style='width: "+(lineHeight*1.25)+"px; height: "+(lineHeight*1.25)+"px;'/> "+result.place_address;
            }
            if((result.place_telephone != "") && (result.place_telephone != null) && (result.place_telephone != undefined)){
                detailString += "<br><img src='./img/call.svg' style='width: "+(lineHeight*1.25)+"px; height: "+(lineHeight*1.25)+"px;'/> "+result.place_telephone;
            }
            if((result.place_email != "") && (result.place_email != null) && (result.place_email != undefined)){
                detailString += "<br><img src='./img/letter.svg' style='width: "+(lineHeight*1.25)+"px; height: "+(lineHeight*1.25)+"px;'/><a href='mailto:"+result.place_email+"'>"+result.place_email+"</a>";
            }
            if((result.place_site != "") && (result.place_site != null) && (result.place_site != undefined)){
                detailString += "<br><img src='./img/www.svg' style='width: "+(lineHeight*1.25)+"px; height: "+(lineHeight*1.25)+"px;'/><a href='"+result.place_site+"'>официальный сайт</a>";
            }
            if((result.place_id != "") && (result.place_id != null) && (result.place_id != undefined)){
                detailString += "<br><br><button class='button' onclick='onPlaceMarkClick("+result.place_id+");'>Перейти к плану здания</button>";
            }
            return detailString;
        };
        function prepareShopDetailedResult(result){
            var detailString = "";
            if(result.floorNumber){
                detailString += "<img src='./img/stairs.svg' style='width: "+(lineHeight*1.25)+"px; height: "+(lineHeight*1.25)+"px; display: block-inline;'/> " + result.floorNumber + " этаж";
            }
            if(result.description){
                
            }
            if(result.addresses){
                detailString += "<br><img src='./img/marker.svg' style='width: "+(lineHeight*1.25)+"px; height: "+(lineHeight*1.25)+"px;'/> "+result.addresses;
            }
            if(result.phone_numbers){
                detailString += "<br><img src='./img/call.svg' style='width: "+(lineHeight*1.25)+"px; height: "+(lineHeight*1.25)+"px;'/> "+result.phone_numbers;   
            }
            if(result.email_addresses){
                detailString += "<br><img src='./img/letter.svg' style='width: "+(lineHeight*1.25)+"px; height: "+(lineHeight*1.25)+"px;'/><a href='mailto:"+result.email_addresses+"'>"+result.email_addresses+"</a>";
            }
            if(result.sites){
                detailString += "<br><img src='./img/www.svg' style='width: "+(lineHeight*1.25)+"px; height: "+(lineHeight*1.25)+"px;'/><a href='"+result.sites+"'>официальный сайт</a>";
            }
            if(result.categories){
                
            }
            return detailString;
        };
        function addPlaceSearchResultToPanel(result){
            var searchResult = $(
                                    "<div/>",
                                    {
                                        style: "margin-bottom: 5%;",
                                    }
                                );
            var bullet = $(
                            "<div/>", 
                            {
                                style: "display: inline-block; \
                                    position: static; \
                                    border-radius: 50%; \
                                    background-image: -webkit-linear-gradient(top, #00B0D8, #0088C4); \
                                    background-image: -moz-linear-gradient(top, #00B0D8, #0088C4); \
                                    background-image: -o-linear-gradient(top, #00B0D8, #0088C4); \
                                    background-image: -ms-linear-gradient(top, #00B0D8, #0088C4); \
                                    background-image: linear-gradient(top, #00B0D8, #0088C4); \
                                    margin-right: 2%; \
                                    ",
                            }
                        );
            var height = document.getElementById("body").clientHeight;
            bullet.css("height", 0.015*height);
            bullet.css("width", 0.015*height);
            searchResult.append(bullet);
            var textResult = $("<a/>", {html: "<strong>"+result.place_name+"</strong>"});
            searchResult.append(textResult);
            var detailedResult = $(
                                        "<div/>",
                                        {
                                            html:  preparePlaceDetailedResult(result),
                                            style: "width: 100%;\
                                                    display: none;\
                                                    padding-left: 5%;\
                                            ",
                                        }
                                    );
            searchResult.append(detailedResult);
            textResult.click(function(){detailedResult.slideToggle("slow")})
            $("#search_results").append(searchResult);
        };
        function addShopSearchResultToPanel(result){
            var searchResult = $(
                                    "<div/>",
                                    {
                                        style: "margin-bottom: 5%;",
                                    }
                                );
            var bullet = $(
                            "<div/>", 
                            {
                                style: "display: inline-block; \
                                    position: static; \
                                    border-radius: 50%; \
                                    background-image: -webkit-linear-gradient(top, #00B0D8, #0088C4); \
                                    background-image: -moz-linear-gradient(top, #00B0D8, #0088C4); \
                                    background-image: -o-linear-gradient(top, #00B0D8, #0088C4); \
                                    background-image: -ms-linear-gradient(top, #00B0D8, #0088C4); \
                                    background-image: linear-gradient(top, #00B0D8, #0088C4); \
                                    margin-right: 2%; \
                                    ",
                            }
                        );
            var height = document.getElementById("body").clientHeight;
            bullet.css("height", 0.015*height);
            bullet.css("width", 0.015*height);
            searchResult.append(bullet);
            var textResult = $("<a/>", {html: "<strong>"+result.name+"</strong>"});
            searchResult.append(textResult);
            var detailedResult = $(
                                        "<div/>",
                                        {
                                            html:  prepareShopDetailedResult(result),
                                            style: "width: 100%;\
                                                    display: none;\
                                                    padding-left: 5%;\
                                            ",
                                        }
                                    );
            searchResult.append(detailedResult);
            textResult.click(function(){detailedResult.slideToggle("slow")})
            $("#search_results").append(searchResult);
        };
        function cleanupMapFilter(){
            setUpSearchPlaceHolder();
            map.showAllPlaceMarks();
        };
        function onSearch(pattern){
            var autocomplete = $('#autocomplete');
            autocomplete.css("height", "0px");
            autocomplete.css("display", "none");
            tpe.removeAllHighlightings();

            if(savedContexts.index % 2 == 0){ //city place context
                cleanupMapFilter();
                prepareSearchResults(pattern);
                $.get("./php/searchplace.php?pattern="+pattern, 
                    function(data){
                        var search_result = eval(data);
                        var filter = new Array();
                        for(var i=0; i<search_result.length; i++){
                            filter.push(search_result[i].place_id);
                            addPlaceSearchResultToPanel(search_result[i]);
                        };
                        map.filterPlaceMarksByIds(filter);
                    }
                );
            }else{ //building object context
                //TODO: make some search placeholder
                var searchResult = tpe.searchPlanObjectsByName(pattern);
                prepareSearchResults(pattern);
                for(i in searchResult){
                    if(searchResult[i].name){
                        addShopSearchResultToPanel(searchResult[i]);
                    }
                }
            }
        };
        function getAutocompleteVariants(inputValue){
            var variantsSource = null;
            if(savedContexts.index % 2 == 0){
                variantsSource = "./php/get_autocomplete_variants_places.php?pattern=";
            }else{
                variantsSource = "./php/get_autocomplete_variants_shops.php?pattern=";
            }
            $.get(variantsSource+inputValue, 
                function(data){
                    var variants = eval(data);
                    if(variants){
                        var variantList = $("#autocomplete")
                        if(variants.length<=5){
                            for(var i=0; i<variants.length; i++){
                                variantList.append($('<div/>',
                                    {
                                        text:  variants[i],
                                        click: function(){$('#search_box').val($(this).text());},
                                    }
                                ));
                            };
                            variantList.css("display", "block");
                            variantList.animate({height: (variants.length*lineHeight)+"px"});
                        }else{
                            for(var i=0; i<5; i++){
                                variantList.append($('<div/>',
                                    {
                                        text:  variants[i],
                                        click: function(){$('#search_box').val($(this).text());},
                                    }
                                ));
                            }
                            variantList.css("display", "block");
                            variantList.animate({height: (5*lineHeight)+"px"});
                            for(var i=5; i<variants.length; i++){
                                variantList.append($('<div/>',
                                    {
                                        text:  variants[i],
                                        click: function(){$('#search_box').val($(this).text());},
                                    }
                                ));
                            }
                        }
                    }
                }
            );
        };
        //custom event handlers
        function onObjectClick(evt, elementId){
            evt.stopPropagation();
            if(this.was_moved==0){
                var text = this.parseElementInfo(elementId);
                this.removeAllHighlightings();
                this.highlightElement(elementId);
                searchResultPanel.html(null);
                var infoAboutShop = $(
                    "<div/>",
                    {id: "info"}
                );
                infoAboutShop.html(text);
                searchResultPanel.append(infoAboutShop);
            }else{
                this.was_moved=0;
            }
        };
        function onPlanBackGroundClick(evt){
            setUpSearchPlaceHolder();
        }
        require(["dojo/parser", "dojo/ready", "dijit/layout/TabContainer", "dijit/layout/ContentPane", "dijit/layout/BorderContainer"], 
            function(parser, ready, dom, on, textbox, registry){
                parser.parse();// dojo parser call
                map = MapEngines.Google();
                map.initMap(
                	"city_map", 
                	MapTypes.ROADMAP, 
                	new Coords(<?echo mysql_result($query_result, 0, "city_latitude")?>, <?echo mysql_result($query_result, 0, "city_longitude")?>), 
                	<?echo mysql_result($query_result, 0, "city_zoom")?>
                );
                <?
                	$query_result = mysql_query("SELECT place_id, place_name, place_latitude, place_longitude FROM places WHERE city_id=$cityId");
                	while(list($place_id, $place_name, $place_latitude, $place_longitude) = mysql_fetch_row($query_result) ){
                		echo "map.addPlaceMark(new PlaceMark(new Coords($place_latitude, $place_longitude), '$place_name', function(){onPlaceMarkClick($place_id)}, $place_id));\n";
                	};
                ?>
                tpe = new TPlanEngine({parentElementId: 'building_plan', predefinedParentWidth: document.getElementById('city_tab').clientWidth, predefinedParentHeight: document.getElementById('city_tab').clientHeight});
                $('#building_plan').bind('click', onPlanBackGroundClick);
					// init event acceptor (building plan tab switcher)
                $('[widgetId="centralPanel_tablist_building_tab"]').attr('id', "centralPanel_tablist_building_tab");
                planTabButton = document.getElementById("centralPanel_tablist_building_tab");

                // init autocomplete widget
                var autocomplete = document.createElement("div");
                autocomplete.id           = "autocomplete";
                var search_box_rect       = document.getElementById("search_box").getBoundingClientRect();
                autocomplete.style.left   = search_box_rect.left+"px";
                autocomplete.style.top = search_box_rect.bottom+"px";
                autocomplete.style.zIndex = 10;
                autocomplete.style.width  = (search_box_rect.right-search_box_rect.left)+"px";
                autocomplete.style.height = 0;
                autocomplete.style.position = "absolute";
                autocomplete.style.display  = "none";
                autocomplete.style.backgroundColor = "white";
                autocomplete.style.border = "1px solid grey";
                autocomplete.style.overflowX = "hidden";
                autocomplete.style.whiteSpace = "nowrap";
                autocomplete.style.textOverflow = "ellipsis";
                document.getElementById("appLayout").appendChild(autocomplete);
                var search_box    = $("#search_box");
                var search_button = $("#search_button")
                var jautocomplete = $("#autocomplete");
                search_button.bind("click", function(){onSearch(search_box.val());});
                search_box.bind("input",function(){
                        if(search_box.val().length == 0){
                            jautocomplete.css("height", "0px");
                            jautocomplete.css("display", "none");
                            jautocomplete.html(null);
                            if(savedContexts.index % 2 == 0){
                                cleanupMapFilter();
                            }else{
                                setUpSearchPlaceHolder();
                            }
                        }else{
                            jautocomplete.html(null);
                            getAutocompleteVariants(search_box.val());
                        };
                    }
                )
                search_box.bind("keyup", function(evt){
                    if(evt.keyCode === 13){ //if 'Enter' key was pressed
                        onSearch(search_box.val());
                    }
                })
                savedContexts = {index: 0, contexts: Array(new Context($('[widgetId="centralPanel_tablist_building_tab"]')), new Context($('[widgetId="centralPanel_tablist_city_tab"]')))};
                savedContexts.contexts[savedContexts.index].actionElement.click(toggleContext);
                setUpSearchPlaceHolder();
                tpe.setUpShowToolTipFunction(onObjectClick);
            });
        </script>
</html>
